package network.chat.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client implements Serializable {

	private IHMClient clientIHM;

	/**
	 * 
	 */
	private static final long serialVersionUID = 2077472212762775080L;

	private final String id;
	private final InetAddress address;
	private final int port;
	transient private boolean isConnected;
	transient private final Socket socketC; // JAVAHF Ok

	private static int DEFAULT_PORT = 2501;
	private static String ID = "Anonymous";

	public Client() throws IOException, UnknownHostException {
		this.id = ID;
		this.port = DEFAULT_PORT;
		this.address = InetAddress.getLocalHost();
		this.socketC = new Socket(address, port);
		this.isConnected = true;
		go();
	}

	public Client(final String id) throws IOException, UnknownHostException {
		this.id = id;
		this.port = DEFAULT_PORT;
		this.address = InetAddress.getLocalHost();
		this.socketC = new Socket(address, port);
		this.isConnected = true;
		go();
	}

	public Client(final String id, final InetAddress address, final int port)
			throws IOException {
		this.id = id;
		this.address = address;
		this.port = port;
		this.socketC = new Socket(address, port);
		this.isConnected = true;
		go();
	}

	public String getId() {
		return id;
	}

	public void setIHMClient(IHMClient clientIHM) {
		this.clientIHM = clientIHM;
	}

	public void write(String message) throws IOException {
		String messageToSend = this.id + " > " + message;
		PrintWriter out = new PrintWriter(socketC.getOutputStream(), true);
		out.println(messageToSend);
	}

	public void go() throws IOException {
		Reader reader = new Reader();
		reader.start();
	}

	private class Reader extends Thread {
		public Reader() {
		}

		@Override
		public void run() {
			String messageReceived = "Ready to read !!";
			try {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						socketC.getInputStream()));
				while (isConnected) {
					messageReceived = in.readLine();
					System.out.println(messageReceived);
					if (!messageReceived.contains("/ack")) {
						clientIHM.setTextScreen(messageReceived);
					} else {
						String ackCommand = messageReceived.substring(messageReceived.indexOf("/ack") + 4);
						System.out.println("CLIENT " + ackCommand);
						switch (ackCommand) {
						case "quit":
							clientIHM.setTextScreen(messageReceived);
							socketC.close();
							clientIHM.setTextScreen(ackCommand);
							isConnected = false;
							break;
						default:
							break;
						}
					}
				}
			} catch (IOException e) {
				clientIHM.displayException(messageReceived + "\n"
						+ e.getMessage());
			}
		}
	}
}
